package com.tanhua.manage.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.exception.BusinessException;
import com.tanhua.manage.mapper.AdminMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Value("${tanhua.secret}")
    private String secret;
    /**
     * 验证码保存到redis
     * @param uuid 作为验证码key的一部分
     * @param code 存入redis中的验证码
     */
    public void saveCap(String uuid, String code) {
        String key = "MANAGE_CAP_"+uuid;
        redisTemplate.opsForValue().set(key,code, Duration.ofMinutes(5));
    }

    /**
     * 接口名称：用户登录
     */
    public ResponseEntity<Object> login(Map<String, String> map) {
        //1. 获取请求参数
        String username = map.get("username");
        String password = map.get("password");
        String verificationCode = map.get("verificationCode");
        String uuid = map.get("uuid");

        //2. 校验验证码
        //2.1 从redis中获取验证码
        String key = "MANAGE_CAP_"+uuid;
        String redisCode = redisTemplate.opsForValue().get(key);
        //2.2 判断
        if (StringUtils.isEmpty(verificationCode) || StringUtils.isEmpty(redisCode)) {
            throw new BusinessException("验证码为空！");
        }
        if (!verificationCode.equals(redisCode)) {
            throw new BusinessException("验证码校验失败");
        }
        //2.3 删除redis中的验证码
        redisTemplate.delete(key);

        //3. 校验用户名密码
        Admin admin = query().eq("username", username).one();
        if (admin == null || !admin.getPassword().equals(SecureUtil.md5(password))){
            throw new BusinessException("用户名或密码错误！");
        }

        //4. 通过jwt生成token,存储到redis中
        //4.1 生成token
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("id",admin.getId());
        tokenMap.put("username",admin.getUsername());
        String token = Jwts.builder()
                .setClaims(tokenMap).signWith(SignatureAlgorithm.HS256,secret)
                .compact();
        //4.2 对象转换为json
        String adminJsonString = JSON.toJSONString(admin);
        //4.3 存储到redis
        redisTemplate.opsForValue().set("MANAGE_TOKEN_"+token,adminJsonString,Duration.ofMinutes(30));

        //5. 返回token
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("token",token);
        return ResponseEntity.ok(resultMap);
    }

    /**
     * 根据token，解析得到Admin对象
     */
    public Admin findUserByToken(String token) {
        // 获取redis中的json字符串
        String adminJsonString = redisTemplate.opsForValue().get("MANAGE_TOKEN_" + token);
        // string--->admin
        Admin admin = JSON.parseObject(adminJsonString, Admin.class);
        // 更新redis中的token有效时间
        redisTemplate.opsForValue().set("MANAGE_TOKEN_"+token,adminJsonString,Duration.ofMinutes(30));
        return admin;
    }

    /**
     * 接口名称：用户登出
     * @param token
     * @return
     */
    public ResponseEntity<Object> logout(String token) {
        redisTemplate.delete("MANAGE_TOKEN_"+token);
        return ResponseEntity.ok(null);
    }
}
